﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using TyMES.ViewModel.Record.AlarmLogRecordVMs;
using TyMES.Model.Record;
using System.Threading.Tasks;
using TyMES.Communication;
using TyMES.Services;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using System.ComponentModel.DataAnnotations;
using Azure;
using System.Configuration;


namespace TyMES.Controllers
{
    [Area("Record")]
    [AuthorizeJwtWithCookie]
    [ActionDescription("报警日志记录")]
    [ApiController]
    [Route("api/AlarmLogRecord")]
	public partial class AlarmLogRecordController : BaseApiController
    {
        private readonly HttpService _httpService;
        private PassStationService _passageService;
        private readonly IConfiguration _configuration;
        private string _LineCode;
        private string factoryCode;
        private string mesIP;
        private string mesPort;
        public AlarmLogRecordController(HttpService httpService, PassStationService passageService, IConfiguration configuration)
        {
            _httpService = httpService;
            _passageService = passageService;
            this._LineCode = configuration["LineCode"];
            this.factoryCode = configuration["FactoryCode"];
            this.mesIP = configuration["MESIP"];
            this.mesPort = configuration["MESPORT"];
        }

        [ActionDescription("Sys.Search")]
        [HttpPost("Search")]
		public IActionResult Search(AlarmLogRecordSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<AlarmLogRecordListVM>(passInit: true);
                vm.Searcher = searcher;
                return Content(vm.GetJson());
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public AlarmLogRecordVM Get(string id)
        {
            var vm = Wtm.CreateVM<AlarmLogRecordVM>(id);
            return vm;
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("Add")]
        public IActionResult Add(AlarmLogRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("报警日志记录")]
        [HttpPost("AlarmLogAdd")]

        public async Task<ResponseBase> AlarmLogAdd(AlarmLogRecord record)
        {
            record.operationCode=_passageService.ExstractOperation(record.stationCode);
            record.lineCode = _LineCode;
            record.warningTime = DateTime.Now;
            record.warningCode = await FillZero(record.warningCode);

            try
            {
                AlarmRequestBody request = new AlarmRequestBody();
                request = PackAlarmData(record);
                string psd = JsonConvert.SerializeObject(request);
                string value = await _httpService.PostDataAsync("http://"+mesIP+":"+mesPort+"/api/product/Product_Information", psd);
                Alarmresponse response = JsonConvert.DeserializeObject<Alarmresponse>(value);
                if (response.data.code == "000000")
                {
                    record.warningType = record.warningCode;
                    DC.Set<AlarmLogRecord>().Add(record);
                    DC.SaveChanges();
                    return new ResponseBase(true, "报警信息上传成功");
                }
                else
                {
                    DC.Set<AlarmLogRecord>().Add(record);
                    DC.SaveChanges();
                    return new ResponseBase(true, "报警信息上传失败"+":" + response.data.mesg +":"+ response.data.data);
                }
            }
            catch (Exception ex)
            {
                DC.Set<AlarmLogRecord>().Add(record);
                DC.SaveChanges();
                return new ResponseBase(true, ex.Message);
            }


        }


        public async Task<string> FillZero(string wariningCode)
        {
            if (wariningCode.StartsWith("DM1-"))
            {
                string suffix = wariningCode.Substring("DM1-".Length);
                if (suffix.Length == 1)
                {
                    return "DM1-" + "0" + suffix;
                }
                return wariningCode;
            }
            else
                return wariningCode;
        }

        /// <summary>
        /// 打包报警数据
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public AlarmRequestBody PackAlarmData(AlarmLogRecord record)
        {
            AlarmRequestBody request = new AlarmRequestBody();
            request.data = new List<AlarmRequestData>();
            AlarmRequestData data = new AlarmRequestData();
            data.lineCode = record.lineCode;
            data.operationCode = record.operationCode;
            data.stationCode = record.stationCode;
            data.machineCode = record.machineCode;
            data.warningCode = record.warningCode;
            data.warningType = record.warningType;
            data.warningDesc = record.warningDesc;
            data.warningTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            request.data.Add(data);
            request.requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            return request;
        }
        public class AlarmRequestBody
        {
            public string serviceId = "System001_Warning";
            public string factoryCode = "TH13";
            public string requestTime { get; set; }
            public List<AlarmRequestData> data { get; set; }
        }
        public class AlarmRequestData
        {
            public string lineCode { get; set; }

            public string stationCode { get; set; }

            public string operationCode { get; set; }

            public string machineCode { get; set; }

            public string warningCode { get; set; }

            public string warningType { get; set; }

            public string warningDesc { get; set; }
            public string warningTime { get; set; }
        }

        public class Alarmresponse
        {
            public string code { get; set; }
            public bool success { get; set; }
            public bool fail { get; set; }
            public string mesg { get; set; }
            public alarmresponseMes data { get; set; }
            public string time { get; set; }
        }
        public class alarmresponseMes
        {
            public string code { get; set; }
            public bool success { get; set; }
            public bool fail { get; set; }
            public string mesg { get; set; }
            public string data { get; set; }
            public string time { get; set; }
        }
        [ActionDescription("Sys.Edit")]
        [HttpPut("Edit")]
        public IActionResult Edit(AlarmLogRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoEdit(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<AlarmLogRecordBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }


        [ActionDescription("Sys.Export")]
        [HttpPost("ExportExcel")]
        public IActionResult ExportExcel(AlarmLogRecordSearcher searcher)
        {
            var vm = Wtm.CreateVM<AlarmLogRecordListVM>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("ExportExcelByIds")]
        public IActionResult ExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<AlarmLogRecordListVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<AlarmLogRecordImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(AlarmLogRecordImportVM vm)
        {
            if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()))
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm?.EntityList?.Count ?? 0);
            }
        }


    }
}
